"use client"

import { useState } from "react";
import { useRouter } from 'next/navigation';
import { useAuth } from "@/context/AuthContext";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const formSchema = z.object({
  account: z.string().min(1, { message: "请输入您的账号" }),
  password: z.string().min(6, { message: "密码不能少于6个字符" }),
});

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { login } = useAuth();
  const router = useRouter();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      account: "",
      password: "",
    },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch("/login/verification", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          account: values.account,
          password: values.password,
          source: "1",
        }),
      });

      if (!response.ok) {
        let errorMessage = "登录失败";
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } catch (jsonError) {
          const errorText = await response.text();
          console.error("Login failed with non-JSON response:", errorText);
          errorMessage = "登录时发生未知错误。";
        }
        throw new Error(errorMessage);
      }

      await login('');
      router.push('/dashboard');
    } catch (err: any) {
      console.error("Login failed:", err);
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="flex items-center justify-center min-h-screen bg-white">
      <div className="w-full max-w-sm">
        <div className="text-left mb-6">
          <span className="bg-yellow-300 text-black px-2 py-1 font-bold text-lg inline-block">登录</span>
        </div>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="grid w-full items-center gap-2">
            <Label htmlFor="account">账号*</Label>
            <Input {...form.register("account")} id="account" placeholder="请输入账号" />
            {form.formState.errors.account && (
              <p className="text-red-500 text-xs">{form.formState.errors.account.message}</p>
            )}
          </div>
          <div className="grid w-full items-center gap-2">
            <Label htmlFor="password">密码*</Label>
            <Input {...form.register("password")} type="password" id="password" placeholder="请输入密码" />
            {form.formState.errors.password && (
              <p className="text-red-500 text-xs">{form.formState.errors.password.message}</p>
            )}
          </div>
                    {error && <p className="text-red-500 text-xs text-center">{error}</p>}
          <Button type="submit" disabled={isLoading} className="w-full bg-black text-white hover:bg-gray-800 font-bold">
            {isLoading ? "登录中..." : "登录"}
          </Button>
        </form>
        <p className="text-center text-sm text-gray-600 mt-6">
          没有账号？
          <a href="/register" className="text-blue-600 hover:underline">
            立即注册
          </a>
        </p>
      </div>
    </div>
  );
}